import 'dart:convert';
import 'dart:io';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart' ;
import 'package:flutter/services.dart';
import 'package:flutter_native_image/flutter_native_image.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:image_picker/image_picker.dart';
import 'package:mfkb/config/Config.dart';
import 'package:mfkb/pages/login.dart';
import 'package:mfkb/pages/userinfo.dart';
import 'package:mfkb/plugin/MyBehavior.dart';
import 'package:mfkb/service/UserService.dart';
import 'package:simple_image_crop/simple_image_crop.dart';
import 'package:toast/toast.dart';

class Setting extends StatefulWidget {
  @override
  _SettingState createState() => _SettingState();
}

enum _sheetType { gallery, camera }

class _SettingState extends State<Setting> {

  dynamic user ;
  bool canUpload = false ;
  String nickname ;
  String room ;
  String phone ;
  String wx ;
  String icon ;
  File _image ;

  @override
  void initState() {
    super.initState();
    String d = Config().getUserInfo() ;
    if(d != null){
      dynamic userInfo = jsonDecode(d) ;
      // if(userInfo["nickname"] == null || userInfo["nickname"] == ""
      //   || userInfo["icon"] == null || userInfo["icon"] == "" 
      //   || userInfo["gender"] == null || userInfo["gender"] == ""){
      //   //Navigator.of(context).pop() ;
      //   Navigator.of(context).pushReplacement(MaterialPageRoute(builder: (_){
      //     return UserFullDataPage() ;
      //   })) ;
      // }
      user = userInfo ;
      icon = user["icon"] ;
      room = user["room"] ;
      phone = user["phone"] ;
      nickname = user["nickname"] ;
      wx = user["wx"] ;
      setState(() {});
    }else{
      Navigator.of(context).pushReplacement(MaterialPageRoute(builder: (_){
        return LoginWidge() ;
      })) ;
    }
  }

  final cropKey = GlobalKey<ImgCropState>();

  Future getImage(type) async {
    File image = await ImagePicker.pickImage(
        source: type == _sheetType.gallery
            ? ImageSource.gallery
            : ImageSource.camera);
    if (image == null) return;
    Navigator.of(context).pop();
    _image = await Navigator.of(context).push(MaterialPageRoute(builder: (_){
      return SimpleCropRoute(image) ;
    })) ; //pushNamed('crop_page', arguments: {'image': image});
    if(_image != null){
      canUpload = true ;
      // 图片上传

    }
  }

  void _showActionSheet() {
    showModalBottomSheet(
      context: context,
      builder: (BuildContext context) {
        return SafeArea(
          child: Column(
            mainAxisSize: MainAxisSize.min, // 设置最小的弹出
            children: <Widget>[
              new ListTile(
                leading: new Icon(Icons.photo_camera),
                title: new Text("相机拍照"),
                onTap: () async {
                  await getImage(_sheetType.camera);
                },
              ),
              new ListTile(
                leading: new Icon(Icons.photo_library),
                title: new Text("相册选择"),
                onTap: () async {
                  await getImage(_sheetType.gallery);
                },
              ),
            ],
          ),
        );
      });
  }

  @override
  Widget build(BuildContext context) {
    return AnnotatedRegion<SystemUiOverlayStyle>(
      value: SystemUiOverlayStyle.dark ,
      child: Scaffold(
        body: Container(
          color: Color.fromARGB(255, 246, 246, 248),
          child:Column(
            children: <Widget>[
              Container(
                height: MediaQuery.of(context).padding.top ,
              ) ,
              Container(
                height: 45,
                child: Row(
                  children: <Widget>[
                    Container(
                      width: 17,
                      height: 17,
                      margin: EdgeInsets.only(left:ScreenUtil().setWidth(19)),
                      child: GestureDetector(
                        child: Container(
                          width: 17,
                          height: 17,
                          child: Image.asset("assets/images/back.png" , fit: BoxFit.fill,),
                        ),
                        onTap: (){
                          Navigator.of(context).pop() ;
                        },
                      ),
                    ) ,
                    Expanded(
                      child: Container(
                        child: Center(
                          child: Text("设置" , style: TextStyle(
                            color: Color.fromARGB(255, 19 , 28 , 53) ,
                            fontSize: ScreenUtil().setSp(18) ,
                            fontWeight: FontWeight.bold 
                          ),),
                        ),
                      ),
                    ) ,
                    Container(
                      height: 17,
                      width: 36,
                    )
                  ],
                ),
              )  ,
              Expanded(
                child: ScrollConfiguration(
                  behavior: MyBehavior() ,
                  child: ListView(
                    padding: EdgeInsets.all(0) ,
                    children: <Widget>[
                      Container(
                        height: ScreenUtil().setHeight(114),
                        margin: EdgeInsets.only(left:ScreenUtil().setWidth(15) , right:ScreenUtil().setWidth(15) , top:ScreenUtil().setHeight(8)),
                        decoration: BoxDecoration(
                          color: Colors.white ,
                          borderRadius: BorderRadius.all(Radius.circular(8))
                        ),
                        child: Column(
                          children: <Widget>[
                            GestureDetector(
                              child: Container(
                                height: ScreenUtil().setHeight(56),
                                color: Color.fromARGB(0, 0, 0, 0),
                                child: Row(
                                  children: <Widget>[
                                    Expanded(
                                      child: Container(
                                        margin: EdgeInsets.only(left:ScreenUtil().setWidth(13)),
                                        child: Text("头像" , style: TextStyle(
                                          fontSize: ScreenUtil().setSp(14) ,
                                          color: Color.fromARGB(255, 19, 28, 53) ,
                                          fontWeight: FontWeight.w500
                                        ),),
                                      ),
                                    ) ,
                                    Container(
                                      width: ScreenUtil().setHeight(38),
                                      height: ScreenUtil().setHeight(38),
                                      margin: EdgeInsets.only(right:ScreenUtil().setWidth(10)),
                                      child: ClipRRect(
                                        borderRadius: BorderRadius.all(Radius.circular(ScreenUtil().setHeight(19))),
                                        child: _image == null ? CachedNetworkImage(
                                          imageUrl: Config().getImgHost() + (icon == null ? "" : icon) ,
                                          placeholder: (context , url){
                                            return (
                                              Container(
                                                color: Color.fromARGB(255, 246, 245, 248),
                                                child: Center(
                                                  child: Image.asset("assets/images/imageloading.png"),
                                                ),
                                              )
                                            ) ;
                                          },
                                        ) : Image(image: FileImage(_image),),
                                      ) ,
                                    ) ,
                                    Container(
                                      height: ScreenUtil().setHeight(16) ,
                                      width: ScreenUtil().setHeight(16) ,
                                      margin: EdgeInsets.only(right:ScreenUtil().setWidth(10)),
                                      child: Image.asset("assets/images/more_2x.png" , fit:BoxFit.fill),
                                    )
                                  ],
                                ),
                              ),
                              onTap: (){
                                _showActionSheet() ;
                              },
                            ) ,
                            Container(
                              height: 1 ,
                              margin: EdgeInsets.only(left:ScreenUtil().setWidth(13) , right:ScreenUtil().setWidth(12)),
                              color: Color.fromARGB(255, 236, 237, 241),
                            ) ,
                            Expanded(
                              child: Container(
                                child: Row(
                                  children: <Widget>[
                                    Container(
                                      margin: EdgeInsets.only(left:ScreenUtil().setWidth(13)),
                                      child: Text("昵称" , style: TextStyle(
                                        fontSize: ScreenUtil().setSp(14) ,
                                        color: Color.fromARGB(255, 19, 28, 53) ,
                                        fontWeight: FontWeight.w500
                                      ),),
                                    ),
                                    Expanded(
                                      child:Container(
                                        margin: EdgeInsets.only(right:ScreenUtil().setWidth(12)),
                                        child: TextField(
                                          textAlign: TextAlign.end ,
                                          decoration: InputDecoration(
                                            border: InputBorder.none 
                                          ),
                                          controller: TextEditingController.fromValue(TextEditingValue(
                                            text: '${nickname == null ? "" : nickname}',  //判断keyword是否为空
                                            // 保持光标在最后
                                            selection: TextSelection.fromPosition(TextPosition(
                                                affinity: TextAffinity.downstream,
                                                offset: '${nickname}'.length))
                                            )
                                          ),
                                          onChanged: (value){
                                            if(nickname != value){
                                              canUpload = true ;
                                              nickname = value ;
                                              setState(() {});
                                            }
                                          },
                                        )
                                      ) ,
                                    )
                                  ],
                                ),
                              ),
                            )
                          ],
                        ),
                      ) ,
                      Container(
                        margin: EdgeInsets.only(top:ScreenUtil().setHeight(4) , left:ScreenUtil().setWidth(15) , right:ScreenUtil().setWidth(15)),
                        child: Column(
                          children: <Widget>[
                            item("宿舍地址" , room == null ? "" : room , false , (value){
                              if(room != value){
                                canUpload = true ;
                                room = value ;
                                setState(() {});
                              }
                            }) ,
                            item("手机号" , phone == null ? "" : phone , false , (value){
                              if(phone != value){
                                canUpload = true ;
                                phone = value ;
                                setState(() {});
                              }
                            }) ,
                            item("微信号" , wx == null ? "" : wx , false , (value){
                              if(wx != value){
                                canUpload = true ;
                                wx = value ;
                                setState(() {});
                              }
                            }) ,
                          ],
                        ),
                      ) ,
                      Visibility(
                        visible: canUpload ,
                        child: GestureDetector(
                          child: Container(
                            margin: EdgeInsets.only(left:ScreenUtil().setWidth(15) , right:ScreenUtil().setWidth(15) , top:ScreenUtil().setHeight(40)) ,
                            height: ScreenUtil().setHeight(48) ,
                            decoration: BoxDecoration(
                              color: Color.fromARGB(255, 0, 195, 206) ,
                              borderRadius: BorderRadius.all(Radius.circular(8)) ,
                              boxShadow: [
                                BoxShadow(
                                  color: Color.fromARGB(50, 0, 0, 0) ,
                                  blurRadius: 2 ,
                                  offset: Offset(0 , 1)
                                )
                              ]
                            ),
                            child: Center(
                              child: Text("保存" , style: TextStyle(
                                fontSize: ScreenUtil().setSp(16) ,
                                color: Colors.white ,
                                fontWeight: FontWeight.bold 
                              ),),
                            ),
                          ) ,
                          onTap: () async{
                            FocusScope.of(context).requestFocus(FocusNode());
                            File img = null ;
                            if(_image != null){
                              int len = _image.lengthSync() ;
                              if(len > 1024*1024*9){
                                Toast.show("文件太大", context) ;
                                return ;
                              }
                              img = await FlutterNativeImage.compressImage(
                                _image.path ,
                                // quality: 80 ,
                                // percentage: 100
                              ) ;
                            }
                            bool res = await UserService().updateUserInfo(_image, nickname, phone, room, wx) ;
                            if(res){
                              Toast.show("修改成功", context) ;
                            }else{
                              Toast.show("修改失败", context) ;
                            }
                          },
                        )
                      ) ,
                      GestureDetector(
                        child: Container(
                          height: ScreenUtil().setHeight(48),
                          margin: EdgeInsets.only(left:ScreenUtil().setWidth(15) , right:ScreenUtil().setWidth(15) , top:ScreenUtil().setHeight(canUpload ? 16 : 40)) ,
                          decoration: BoxDecoration(
                            color: Colors.white ,
                            borderRadius: BorderRadius.all(Radius.circular(8)) ,
                            boxShadow: [
                              BoxShadow(
                                color: Color.fromARGB(50, 0, 0, 0) ,
                                blurRadius: 2 ,
                                offset: Offset(0 , 1)
                              )
                            ]
                          ),
                          child: Center(
                            child: Text("退出登录" , style: TextStyle(
                              fontSize: ScreenUtil().setSp(16) ,
                              color: Color.fromARGB(255, 249, 73, 47) ,
                              fontWeight: FontWeight.bold 
                            ),),
                          )
                        ),
                        onTap: (){
                          FocusScope.of(context).requestFocus(FocusNode());
                          Navigator.of(context).push(MaterialPageRoute(builder: (_){
                            return LoginWidge() ;
                          })) ;
                        },
                      )
                    ],
                  ),
                ),
              )
            ],
          ) ,
        ),
      ),
    );
  }

  item(String title , String value , bool hasMore , onChange){
    return Container(
      height: ScreenUtil().setHeight(56),
      margin: EdgeInsets.only(top:ScreenUtil().setHeight(8)),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.all(Radius.circular(8))
      ),
      child: Row(
        children: <Widget>[
          Container(
            margin: EdgeInsets.only(left:ScreenUtil().setWidth(13)),
            child: Text(title , style: TextStyle(
              fontSize: ScreenUtil().setSp(14) ,
              color: Color.fromARGB(255, 19, 28, 53) ,
              fontWeight: FontWeight.w500
            ),),
          ),
          Expanded(
            child:Container(
              margin: EdgeInsets.only(right:ScreenUtil().setWidth(12)),
              child: TextField(
                textAlign: TextAlign.end ,
                decoration: InputDecoration(
                  border: InputBorder.none 
                ),
                controller: TextEditingController.fromValue(TextEditingValue(
                  text: '${value == null ? "" : value}',  //判断keyword是否为空
                  // 保持光标在最后
                  selection: TextSelection.fromPosition(TextPosition(
                      affinity: TextAffinity.downstream,
                      offset: '${value}'.length))
                  )
                ),
                onChanged: (value){
                  if(onChange != null){
                    onChange(value) ;
                  }
                },
              )
            ) ,
          )
        ],
      ),
    ) ;
  }
}